const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const { v4: uuidv4 } = require('uuid');

const userSchema = new mongoose.Schema({
  id: {
    type: String,
    required: true,
    unique: true,
    default: () => uuidv4()
  },
  username: {
    type: String,
    required: [true, '用户名是必需的'],
    unique: true,
    trim: true,
    description: '用户名'
  },
  password: {
    type: String,
    required: [true, '密码是必需的'],
    minlength: 6,
    select: false,
    description: '密码'
  },
  nickName: {
    type: String,
    unique: true,
    trim: true,
    default: '集木——007',
    description: '昵称'
  },
  role: {
    type: String,
    // enum: ['user', 'admin'],
    default: 'user',
    description: '用户角色'
  },
  state: {
    type: String,
    default: true,
    description: '用户状态'
  },

  introduction: {
    type: String,
    default: '',
    description: '用户简介'
  },
  avatar: {
    type: String,
    default: '',
    description: '用户头像'
  },
  createdAt: {
    type: Date,
    required: true,
    default: Date.now,
    immutable: true,
    description: '创建时间'
  },
  updatedAt: {
    type: Date,
    required: true,
    default: Date.now,
    description: '更新时间'
  }
}, {
  timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' }
});

// 添加索引
userSchema.index({ id: 1 }, { unique: true });
userSchema.index({ username: 1 }, { unique: true });

// 密码加密中间件
userSchema.pre('save', async function (next) {
  if (!this.isModified('password')) {
    return next();
  }
  this.password = await bcrypt.hash(this.password, 10);
  this.updatedAt = new Date();
  next();
});

// 更新时自动更新 updatedAt
userSchema.pre(['updateOne', 'findOneAndUpdate'], function (next) {
  this._update = this._update || {};
  this._update.updatedAt = new Date();
  next();
});

// 验证密码方法
userSchema.methods.comparePassword = async function (candidatePassword) {
  return await bcrypt.compare(candidatePassword, this.password);
};

module.exports = mongoose.model('User', userSchema); 